import * as preact from 'preact'
import persistStore from 'unissist'
import localStorageAdapter from 'unissist/integrations/localStorageAdapter'
import createStore, { Store } from 'unistore'
import devtools from 'unistore/devtools'
import { Provider } from 'unistore/preact'
import Header from './header'
import Preview from './preview'
import style from './style/app.module.scss'

const { h, Component } = preact

export interface GlobalStore {
  buffer: string
  bufferChanged: boolean
  fileName: string
}

declare global {
  namespace JSX {
    interface IntrinsicElements {
      'lzc-file-picker': any;
    }
  }
}
declare global {
  interface Window {
    lzcSave: any;
    lzcOpen: any;
  }
}

// Global store
export const store = (initialStore: Partial<GlobalStore> = {}) => {
  let store: Store<GlobalStore> = createStore({
    buffer: '',
    bufferChanged: false,
    fileName: '',
    ...initialStore,
  })

  persistStore(store, localStorageAdapter())

  if (process.env.NODE_ENV === 'development') store = devtools(store)
  return store
}

// const storeInst = store()
// async function request (method: string, url: string, data?: string) {
//     let init: RequestInit = {
//         method,
//         cache: 'no-cache',
//         credentials: "include"
//     }
//     if (data) { init.body = data; }

//     let response = await fetch(url, init);
//     let text = await response.text();

//     if (response.status == 201 || response.status == 200) {
//         return text;
//     } else {
//         throw new Error(`HTTP/${response.status}\n\n${text}`);
//     }
// }
// const getLzcFileContentByUrl = async (filename) => {
//   const fileUrl = `/_lzc/files/home/${filename}`;
//   return request("GET", fileUrl)
// }

class MyComponent extends Component {
// export default () => {
  componentDidMount() {
    const getLzcSave = () => {
      const instance = document.getElementById("lzcSaveFile");
      // @ts-expect-error
      return instance._instance.exposed;
    }
    const getLzcOpen = () => {
      const instance = document.getElementById("lzcOpenFile");
      // @ts-expect-error
      return instance._instance.exposed;
    }
    document.addEventListener("DOMContentLoaded", function() { // 不可以添加 async, 会报错导致函数无法正常执行完
      window.lzcSave = getLzcSave();
      const saveInst = document.getElementById("lzcSaveFile");
      // @ts-expect-error
      saveInst.addEventListener('done', raw => {
        window.lzcSave.close();
      })
      window.lzcOpen = getLzcOpen();
      console.log("My Component has mounted!");
      // // @ts-expect-error
      // window.test = await getLzcFileContentByUrl("test2.marpmd");
      // const searchParams = new URLSearchParams(window.location.search);
      // const lzcfile = searchParams.get('file');
      // if (lzcfile) {
        // const t = await getLzcFileContentByUrl(lzcfile);
        // const decoder = new TextDecoder();
        // @ts-ignore
        // const str = decoder.decode(t);
        // storeInst.setState({
        //   buffer: str,
        //   bufferChanged: false,
        //   fileName: "a",
        // })
      // }
    });
  }

  render () {
    return (
      <Provider store={store()}>
        <div class={style.app}>
          <Header />
          <Preview />
          <lzc-file-picker
            id="lzcSaveFile"
            type="saveAs"
            write-file-content
            title="保存文件"
            breadcrumb-root-title="根目录"
          ></lzc-file-picker>
          <lzc-file-picker
            id="lzcOpenFile"
            type="openFile"
            accept="*.md"
            open-file-content
            open-file-content-async
            title="选择文件"
          ></lzc-file-picker>
        </div>
      </Provider>
    )
  }
}

export default MyComponent;